package com.prs.crm.dao.sys.impl;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.sys.MenuDao;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.sys.Menu;
import com.prs.crm.service.sys.MenuService;
import com.prs.crm.service.sys.ModuleService;

public class MenuDaoImpl extends BaseDaoImpl<Menu> implements MenuDao{
	
    private Menu menu;
    
	private MenuService menuService;
	
	@SuppressWarnings("unchecked")
	public 	Collection<Menu> getShortCutMenus()
	{
		return (List<Menu>)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
						
					        	Criteria criteria = session.createCriteria(Menu.class);
					        	criteria.add(Restrictions.eq("shortcut", true));
					        	return criteria.list();
				        }   
				 } );
	}
	
	@SuppressWarnings("unchecked")
	public Collection<Menu> findMenus(final Menu parent,final Person person)
	{
		return (Collection<Menu>)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
							try
							{
								String hql ="select m from Role r left join r.menus m ";
						    	hql+=" where r.id=? ";
						    	if (parent!=null)
						    		hql+=" and  m.parent=? ";
					        	else
					        		hql+=" and  m.parent is null ";
						    	hql+="order by m.sequence asc,m.id asc";
						    	Query query = session.createQuery(hql);
						    	query.setParameter(0, person.getRole().getId());
						    	if (parent!=null)
						    		query.setParameter(1, parent);
						    	
						    	return query.list();
					        /*	Criteria criteria = session.createCriteria(Role.class,"r");
					        	criteria.createAlias("r.menus", "m",CriteriaSpecification.LEFT_JOIN);
					        	if (person!=null && person.getRole()!=null)
					        	{
					        		criteria.add(Restrictions.eq("r.id", person.getRole().getId()));
					        	}
					        	
					        	criteria.setResultTransformer(CriteriaSpecification.PROJECTION);
					        	criteria.setProjection(Projections.property("menus"));
					        	if (parent!=null)
					        		criteria.add(Restrictions.eq("m.parent",parent));
					        	else
					        		criteria.add(Restrictions.isNull("m.parent"));
					        
					        	criteria.addOrder(Order.asc("m.sequence"));
					        	return criteria.list();*/
							}
							catch (Exception e)
							{
								e.printStackTrace();
								return null;
							}
				        }   
				 } );
	}
	
	@SuppressWarnings("unchecked")
	public 	List<Menu> getRootMenus()
	{
		return (List<Menu>)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
						
					        	Criteria criteria = session.createCriteria(Menu.class);
					        	criteria.add(Restrictions.isNull("parent"));
					        	criteria.addOrder(Order.asc("sequence"));
					        	return criteria.list();
				        }   
				 } );
	}
	@SuppressWarnings("unchecked")
	public Menu findFirstBeforeMenu(final Menu parentMenu,final Integer sequence)
	{
		return (Menu)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
				        @SuppressWarnings("unchecked")
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Menu.class);
				        	if (parentMenu != null)
				        		criteria.add(Restrictions.eq("parent", parentMenu));
				        	else
				        		criteria.add(Restrictions.isNull("parent"));
				        	criteria.add(Restrictions.lt("sequence", sequence));
				        	criteria.addOrder(Order.desc("sequence"));
				        	List<Menu> result = criteria.setMaxResults(1).list();
				        	if (result.size()>0)
				        		return result.get(0);
				        	else
				        		return null;
				        }   
				 } );
	}
	@SuppressWarnings("unchecked")
	public Menu findFirstAfterMenu(final Menu parentMenu,final Integer sequence)
	{
		return (Menu)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
				        @SuppressWarnings("unchecked")
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Menu.class);
				        	if (parentMenu != null)
				        		criteria.add(Restrictions.eq("parent", parentMenu));
				        	else
				        		criteria.add(Restrictions.isNull("parent"));
				        	criteria.add(Restrictions.gt("sequence", sequence));
				        	criteria.addOrder(Order.asc("sequence"));
				        	List<Menu> result = criteria.setMaxResults(1).list();
				        	if (result.size()>0)
				        		return result.get(0);
				        	else
				        		return null;
				        }   
				 } );
	}
	
	@SuppressWarnings("unchecked")
	public Menu findBySequence(final Menu parentMenu,final Integer sequence)
	{
		return (Menu)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
				        @SuppressWarnings("unchecked")
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Menu.class);
				        	if (parentMenu != null)
				        		criteria.add(Restrictions.eq("parent", parentMenu));
				        	else
				        		criteria.add(Restrictions.isNull("parent"));
				        	criteria.add(Restrictions.eq("sequence", sequence));
				        	List<Menu> result = criteria.list();
				        	if (result.size()>0)
				        		return result.get(0);
				        	else
				        		return null;
				        }   
				 } );
	}
	
	@SuppressWarnings("unchecked")
	public Integer getMaxSequence(final Menu parentMenu)
	{
		return (Integer)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Menu.class);
				        	if (parentMenu!=null)
				        		criteria.add(Restrictions.eq("parent", parentMenu));
				        	else
				        		criteria.add(Restrictions.isNull("parent"));
				        	criteria.setProjection(Projections.max("sequence"));
				        	return criteria.uniqueResult();
				        }   
				 } );
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Menu> getChildMenu(final Menu menu) {
		// TODO Auto-generated method stub
		return (Collection<Menu>) this.getHibernateTemplate().execute(new HibernateCallback(){
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = session.createCriteria(Menu.class);
				if(menu != null){
					criteria.add(Restrictions.eq("parent", menu));
				}
				else
				{
					criteria.add(Restrictions.isNull("parent"));
				}
	        	criteria.addOrder(Order.asc("sequence"));
				return criteria.list();
			}
			
		});
	}

	/**
	 * 批量删除
	 * 
	 * JohnLan
	 */
	public boolean bachDelMenu(Integer[] ids) {

		if(ids!=null)
		{
			for(Integer id:ids)
			{
				Menu   menuOb=this.getMenuService().get(id);
				if(menuOb!=null)
				{
		//根据text名字查询 数据			
		String hql="SELECT id FROM Menu WHERE text='"+menuOb.getText()+"'";			
		List  codList=this.getMenuService().getCurrentOb(hql);	
		
		for(Object str:codList)
		{
		//删除中间表中的值 
		String hql1="DELETE FROM hr_role_sys_menu WHERE menus_id='"+str+"'";	
		this.getMenuService().delData(hql1);
		//根据 id值查询数据
		String hql2="SELECT id FROM Menu WHERE parent='"+str+"'";			
		List  codList1=this.getMenuService().getCurrentOb(hql2);
		
		
		
		}
		
					
				}
			}
			
			
			
			
		}
		
		return false;
	}
	
	
	/**
	 * 返回查询结果
	 */
	@SuppressWarnings("unchecked")
	public List getCurrentOb(final String sql) {
		
		return (List)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
							try
							{
						    	Query query = session.createQuery(sql);
						    	return query.list();
					       
							}
							catch (Exception e)
							{
								e.printStackTrace();
								return null;
							}
				        }   
				 } );
	}
	
	/**
	 * 删除
	 * @param hql
	 * @return
	 */
	public Integer delData(final String hql) {
		

		return (Integer)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
							try
							{
						    	Query query = session.createQuery(hql);
						    	return query.executeUpdate();
					       
							}
							catch (Exception e)
							{
								e.printStackTrace();
								return null;
							}
				        }   
				 } );
	}
	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Menu> getAllMenu() {
		Criteria criteria=this.getSession().createCriteria(Menu.class);
		criteria.add(Restrictions.isNotNull("parent"));
		return criteria.list();
	}
	

	
	
}
